﻿#pragma once

#include <osg/Camera>
#include <osgDB/WriteFile>
#include <QDateTime>
#include <QDebug>

class CaptureCallback : public osg::Camera::DrawCallback
{
public:
    explicit CaptureCallback(const std::string& savePath)
        : _savePath(savePath), _captured(false) {}

    virtual void operator()(osg::RenderInfo& renderInfo) const override
    {
        if (_captured) return;  // 避免多次截图
        _captured = true;

        int width = renderInfo.getCurrentCamera()->getViewport()->width();
        int height = renderInfo.getCurrentCamera()->getViewport()->height();

        osg::ref_ptr<osg::Image> image = new osg::Image();
        image->readPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE);

        QString fileName = QString("%1/screenshot_%2.png")
                               .arg(QString::fromStdString(_savePath))
                               .arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss_zzz"));

        if (osgDB::writeImageFile(*image, fileName.toStdString()))
            qDebug() << "截图成功：" << fileName;
        else
            qDebug() << "保存失败：" << fileName;

        // 关键！截图后把回调清除，防止下帧继续触发
        osg::Camera* camera = renderInfo.getCurrentCamera();
        if (camera)
            camera->setFinalDrawCallback(nullptr);
    }

private:
    std::string _savePath;
    mutable bool _captured;
};
